from django.contrib.auth import get_user_model
from rest_framework import serializers

from apps.post.models import Post, Type, Topic


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        fields = ('username', 'avatar', 'date_joined')


class TypesSerializer(serializers.ModelSerializer):
    post_nums = serializers.SerializerMethodField()

    class Meta:
        model = Type
        fields = '__all__'

    def get_post_nums(self, obj):
        return obj.posts.count()


class TopicsSerializer(serializers.ModelSerializer):
    author = UserSerializer(read_only=True)
    post_nums = serializers.SerializerMethodField(read_only=True)
    author_id = serializers.CharField(write_only=True, required=False)

    class Meta:
        model = Topic
        fields = '__all__'

    def get_post_nums(self, obj):
        return obj.posts.count()


class PostsSerializer(serializers.ModelSerializer):
    """
    type_id: post put 时候 type 的 pk
    topic_id: post put 时候 topic 的 pk
    """
    author = UserSerializer(read_only=True)
    type_id = serializers.IntegerField(write_only=True, required=False)
    topic_id = serializers.CharField(write_only=True, required=False)
    author_id = serializers.CharField(write_only=True, required=False)

    class Meta:
        model = Post
        fields = '__all__'
        depth = 1

    def validate_type_id(self, type_id):
        return type_id if type_id else None  # int 为 0 就清空

    def validate_topic_id(self, topic_id):
        return topic_id if topic_id != '0' else None  # str 为'0'就清空


class FileSerializer(serializers.Serializer):
    """
    图片上传
    """
    file = serializers.FileField()

    class Meta:
        fields = ('file',)
